package com.yonyou.crm.sprc.lead.appctrl;

import java.util.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.yonyou.crm.bpub.list.entity.AppListVO;
import com.yonyou.crm.bpub.list.entity.AppListValueVO;
import com.yonyou.crm.common.base.AppBaseCtrl;
import com.yonyou.crm.common.exception.CrmMessageException;
import com.yonyou.crm.common.page.entity.Page;
import com.yonyou.crm.common.rest.apputil.AppRequestUtil;
import com.yonyou.crm.common.rest.constant.AppCodeConstant;
import com.yonyou.crm.common.rest.constant.HttpKeyConstant;
import com.yonyou.crm.common.rest.util.RequestUtil;
import com.yonyou.crm.common.rest.util.ResponseUtil;
import com.yonyou.crm.common.sort.entity.AppSortPlanEnum;
import com.yonyou.crm.sprc.lead.entity.LeadVO;
import com.yonyou.crm.sprc.lead.rmitf.ILeadRmService;

@RestController
@RequestMapping(value = "/{version}/msprc/leads")
public class AppLeadCtrl  extends AppBaseCtrl {

	@Autowired
	private ILeadRmService service;
	
	/**
	 * 列表
	 * @param request
	 * @param response
	 * @return
	 * @throws CrmMessageException 
	 */
	@RequestMapping(method = RequestMethod.GET)
	public Object list(HttpServletRequest request, HttpServletResponse response) throws CrmMessageException {

		JSONObject paramObject = RequestUtil.getParamObject(request);
		
		Integer page = Integer.valueOf(paramObject.getString(HttpKeyConstant.Page));
		Integer pageSize = Integer.valueOf(paramObject.getString(HttpKeyConstant.PageSize));
		checkPageInfo(page, pageSize);
		Page<LeadVO> pageInfo = new Page<LeadVO>(page, pageSize);

		Map<String, Object> searchMap = new HashMap<String, Object>();
		getSearchKeyForList(paramObject, searchMap); //搜索关键字
		getFilterForList(paramObject, searchMap); //列表筛选
		getOptionForList(paramObject, searchMap); //列表数据分类
		getSortOrderForPage(paramObject, pageInfo); //排序依据
		
		Page<LeadVO> pagelist = service.page(pageInfo, searchMap);
		List<LeadVO> dataList = pagelist.getData();
    	List<AppListVO> list = new ArrayList<AppListVO>();
    	
    	if (dataList != null) {
    		for (int i = 0; i<dataList.size(); i++) {
    			LeadVO lead = dataList.get(i);
    			AppListVO listVO = tranVoToAppListVO(lead);
    			list.add(listVO);
    		}
    	}
		
		Map<String, Object> map = new HashMap<String,Object>();
		map.put("list", list);
		return ResponseUtil.getObject(map);
	}
	
	/**
	 * 将数据转化为App列表数据
	 * @param lead
	 * @return
	 * @throws CrmMessageException
	 */
	public AppListVO tranVoToAppListVO(LeadVO lead) throws CrmMessageException {
		AppListVO listVO = new AppListVO();
		listVO.setId(lead.getId());
		
		List<List<AppListValueVO>> valueList = new ArrayList<>();
		List<AppListValueVO> colList = new ArrayList<>();
		AppListValueVO listValue = new AppListValueVO();
		
		listValue = new AppListValueVO();
		listValue.setItemkey("name");
		listValue.setDisplayvalue(lead.getName());
		colList.add(listValue);
		
		valueList.add(colList);
		colList = new ArrayList<>();
		
		listValue = new AppListValueVO();
		listValue.setItemkey("companyName");
		listValue.setDisplayvalue(lead.getCompanyName() == null ? "" : lead.getCompanyName());
		colList.add(listValue);
		
		listValue = new AppListValueVO();
		listValue.setItemkey("state");
		listValue.setDisplayvalue(lead.getStateName() == null ? "" : lead.getStateName());
		colList.add(listValue);
		
		valueList.add(colList);
		colList = new ArrayList<>();

		listValue = new AppListValueVO();
		listValue.setItemkey("source");
		listValue.setDisplayvalue(lead.getSourceName() == null ? "" : lead.getSourceName());
		colList.add(listValue);
		
		listValue = new AppListValueVO();
		listValue.setItemkey("followTime");
		String displayValue = lead.getFollowTime() == null ? "" : formateDate(lead.getFollowTime(), "yyyy-MM-dd");
		listValue.setDisplayvalue(displayValue);
		colList.add(listValue);

		valueList.add(colList);
		listVO.setValuelist(valueList);
		return listVO;
	}

	/**
	 * 排序依据
	 * @param paramObject
	 * @param pageInfo
	 * @throws CrmMessageException
	 */
	private void getSortOrderForPage(JSONObject paramObject, Page<LeadVO> pageInfo) throws CrmMessageException {
		String sortStr = "";
		String orderStr = "";
		Map<String, String> sortInfo = new HashMap<>();
		getSortForList(paramObject, sortInfo);
		if ((sortInfo != null) && (sortInfo.size() > 0)) {
			orderStr = String.valueOf(sortInfo.get("order"));
			Integer sortNum = Integer.valueOf(String.valueOf(sortInfo.get("field")));
			if (sortNum == AppSortPlanEnum.FOLLOWUPTIME.getValue()) {
				sortStr = "follow_time";
			} else if (sortNum == AppSortPlanEnum.MODIFYTIME.getValue()) {
				sortStr = "sys_modified_time";
			} else {
				sortStr = "id";
				orderStr = "desc";
			}
		}
		pageInfo.setSort(sortStr);
		pageInfo.setOrder(orderStr);
	}
	
	/**
	 * 新增与编辑
	 * @param version
	 * @param id
	 * @param request
	 * @param response
	 * @return
	 * @throws CrmMessageException
	 */
	@RequestMapping(value="/{id}", method = RequestMethod.POST)
	public Object save(@PathVariable("version") String version, @PathVariable("id") Long id, HttpServletRequest request, HttpServletResponse response) throws CrmMessageException {
		JSONObject dataJsonObject = AppRequestUtil.getFormParamObject(request);
		
		LeadVO lead = AppRequestUtil.getVO(dataJsonObject.getJSONObject("header"), LeadVO.class);
		String errorMsg = insertValidator(lead);
		if (!errorMsg.equals("")) {
			throw new CrmMessageException(AppCodeConstant.ServerError, errorMsg);
		}
		
		Map<String, Object> param = new HashMap<String, Object>();
		setBizType(dataJsonObject, param);
		
		if (id.equals(0L)) {
			//relateMap标识是否有关联业务的新增
			Map<String, String> relateMap = (Map<String, String>)dataJsonObject.getJSONObject("relateMap");
			if ( relateMap != null) {
				param.put("relateMap", relateMap);
				lead = service.insert(lead, param);
			} else {
				lead = service.insert(lead);
			}
		} else {
			lead.setId(id);
			lead = service.update(lead);
		}
		
		if (lead.getId() == null) {
			throw new CrmMessageException(AppCodeConstant.ServerError, "获取自增主键失败，未保存成功");
		}
		return ResponseUtil.getObject();
	}
	
	/**
	 * 数据校验
	 * @param lead
	 * @return
	 */
	private String insertValidator(LeadVO lead) {
		String Message = "";
		if (lead == null) {
			Message = "线索实体转换失败";
		}
		if (!StringUtils.isNotBlank(lead.getName())) {
			Message = "姓名不能为空";
        }
		return Message;
	}
	
	/**
	 * 关注线索
	 * @param version
	 * @param id
	 * @param request
	 * @param response
	 * @return
	 * @throws CrmMessageException
	 */
	@RequestMapping(value="/{id}/follow", method = RequestMethod.PUT)
	public Object follow(@PathVariable("version") String version, @PathVariable("id") Long id, HttpServletRequest request, HttpServletResponse response) throws CrmMessageException {
		
		JSONObject paramObject = RequestUtil.getParamObject(request);
		String followState = paramObject.getString("followState");
		
		if (id == null) {
			throw new CrmMessageException(AppCodeConstant.ClientError, "线索id不能为空");
		}
		
		if (followState.equals("N")) {
			service.deleteFollow(id);
		} else if (followState.equals("Y")) {
			service.insertFollow(id);
		} else {
			throw new CrmMessageException(AppCodeConstant.ClientError, "非法线索关注标识");
		}

		return ResponseUtil.getObject();
	}
	
	
}
